package com.wjf.birdfish.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class SSHClientRunner {

	/****
	 * 
	 * @param host
	 *            ip
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @param command
	 *            命令
	 * @return
	 */
	public static String sshRunCommandWithResultString(String host,String username, String password, String command) {
		Connection conn = null;
		Session sess = null;
		ByteArrayOutputStream stdoutOuts = null;
		ByteArrayOutputStream stderrOuts = null;
		String stdoutStr = null;
		String stderrStr = null;
		try {
			conn = new Connection(host);
			conn.connect();
			boolean isAuthenticated = conn.authenticateWithPassword(username,password);

			if (!isAuthenticated) {
				throw new RuntimeException("Authentication failed.");
			}

			sess = conn.openSession();

			
			sess.execCommand(command);

			InputStream stdout = new StreamGobbler(sess.getStdout());
			InputStream stderr = new StreamGobbler(sess.getStderr());
			stdoutOuts = new ByteArrayOutputStream();
			int data = stdout.read();
			while (data != -1) {
				stdoutOuts.write(data);
				data = stdout.read();
			}
			stdoutStr = stdoutOuts.toString();

			stderrOuts = new ByteArrayOutputStream();
			int errData = stderr.read();
			while (errData != -1) {
				stderrOuts.write(errData);
				errData = stderr.read();
			}
			stderrStr = stderrOuts.toString();

		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (sess != null) {
				sess.close();
			}

			if (conn != null) {
				conn.close();
			}
		}

		if(stderrStr !=null && stderrStr.length() > 0 ){
			throw new RuntimeException("errorMessage="+stderrStr);
		}

		return stdoutStr;
	}
}